package utility

import (
	"encoding/json"
	"net/url"
)

// 修改参数
func ChangeParams(values url.Values, aparams map[string]Param) string {
	params := ""
	if len(values) == 0 {
		return values.Encode()
	}
	for k, v := range values {
		aparam, ok := aparams[k]
		if ok && aparam.Target != "" {
			params += aparam.Target + "=" + url.QueryEscape(v[0]) + "&"
			continue
		}
		params += k + "=" + url.QueryEscape(v[0]) + "&"
	}
	params = params[:len(params)-1]
	return params
}

type Item struct {
	Item  string      `json:"item"`
	Value interface{} `json:"value"`
}

// 对返回结果进行处理
func ChangeBody(data []byte, abodys map[string]string, bodyType string) ([]byte, error) {
	if bodyType == "items" {
		var items []Item
		err := json.Unmarshal(data, &items)
		if err != nil {
			return data, err
		}

		rst := make(map[string]interface{}, len(items))
		for _, item := range items {
			Name, ok := abodys[item.Item]
			if ok && Name != "" {
				rst[Name] = item.Value
				continue
			}
			rst[item.Item] = item.Value
		}
		return json.Marshal(rst)
	}
	if bodyType == "array" {
		var items []map[string]interface{}
		err := json.Unmarshal(data, &items)
		if err != nil {
			return data, err
		}
		for _, item := range items {
			for aName, Name := range abodys {
				if item[aName] != nil && Name != "" {
					item[Name] = item[aName]
					delete(item, aName)
				}
			}
		}
		return json.Marshal(items)
	}
	return data, nil
}
